﻿using System;
using System.Collections.Generic;
using System.Linq;
using DAL;
using RenrenApi;

namespace BLL
{
    public static class AllThingBll
    {
        /// <summary>
        /// 添加一个新对象
        /// </summary>
        /// <param name="allThing">AllThing对象</param>
        public static void Insert(AllThing allThing, RenrenApiClient client)
        {
            using (var context = new ModelContainer())
            {
                allThing.Time = DateTime.Now;
                allThing.MarkAsAdded();
                context.AllThings.ApplyChanges(allThing);
                context.SaveChanges();
                var visited = new Dictionary<string, bool>();
                var list = context.AllThings.Where(a => a.ClassId == allThing.ClassId);
                foreach (var thing in list)
                {
                    if (visited.ContainsKey(thing.UserId)) continue;
                    visited.Add(thing.UserId, true);
                    client.SendNotification(thing.UserId,
                                            "您关注的课程<a href=\"http://apps.renren.com/sharecourse/course.aspx?id=" + thing.ClassId + "\">" +
                                            thing.ClassName + "</a>又有了新的消息，去看看吧！");
                }
            }
        }

        /// <summary>
        /// 获得前count个AllThing
        /// </summary>
        /// <param name="count">数量</param>
        /// <returns>列表</returns>
        public static List<AllThing> GetTop(int count)
        {
            using (var context = new ModelContainer())
            {
                return context.AllThings.OrderBy(a => a.Time).Take(count).ToList();
            }
        }
    }
}